package com.jason.fingerprint.fragment;

import java.util.List;

import android.widget.TextView;
import android_serialport_api.SerialPortManager;
import com.jason.fingerprint.ui.LoginActivity;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.utils.SystemTool;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android_serialport_api.FingerprintManager;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.AddLoginInfoReq;
import com.jason.fingerprint.beans.LoginReq;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.PreferenceHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.logic.DatbAddLoginSyncLogic;
import com.jason.fingerprint.logic.LoginSyncLogic;
import com.jason.fingerprint.logic.MatchFingerprintSyncLogic;
import com.jason.fingerprint.ui.HomeActivity;
import com.jason.fingerprint.widget.LoadingDialog;

@SuppressLint("HandlerLeak")
public class FingerPrintLoginFragment extends Fragment implements OnClickListener {

	private static final String TAG = "FingerPrintLoginFragment";
	private static final long LOADING_TIME = 1000L;
	private Context mContext;
	private AppContext mAppContext;
	private Activity mActivity;
	private KJDB mKjdb;

	private int mSize = 0;
	private int mCount = 3;//标示重试次数，默认三次
	
	private List<UserBean> mUserBeans;

	private LoadingDialog mProgressDialog;
	private MatchFingerprintSyncLogic mLogic;
	
	private ImageView mTryFingerImageView;
	private TextView mBackTextView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_fingerprint_login,
				container, false);
		initView(view);
		initData();
		return view;
	}

	private void initView(View view) {
		mTryFingerImageView = (ImageView) view.findViewById(R.id.fingerprint_img_tip);
		mTryFingerImageView.setOnClickListener(this);
		mBackTextView = (TextView) view.findViewById(R.id.fingerprint_back);
		mBackTextView.setOnClickListener(this);
		mBackTextView.setVisibility(View.GONE);
		mContext = getActivity();
		mActivity = getActivity();
		mAppContext = (AppContext) getActivity().getApplication();
		mKjdb = mAppContext.getKjdb();
		mProgressDialog = new LoadingDialog(getActivity());
	}

	private void initData() {
		//初始化指纹信息
		initFinger();
		if (SystemTool.checkNet(mContext)) {
			// TODO 同步数据
			//mKjdb.findAll(UserBean.class);
			mUserBeans = mKjdb.findAll(UserBean.class);
			if (mUserBeans != null && !mUserBeans.isEmpty()) {
				matchFingerPrint();
			}else {
				mProgressDialog.setIsOut(false);
				mProgressDialog.setMessage("请稍等，正在加载数据...");
				mProgressDialog.show();
				login();
			}
		} else {
			// 提示用户开启网络，如果用户开启网络，则继续
			DialogHelper.openNetSettingsDialog(getActivity());
		}
	}
	
	//初始化指纹信息
	private void initFinger(){
//		mLogic = MatchFingerprintSyncLogic.getInstance();
		mLogic = new MatchFingerprintSyncLogic();
//		mLogic.setFingerPrintReader(SerialPortManager.getInstance()
//				.getNewAsyncFingerprint());
		mLogic.setHandle(mFingerpringHandler);
		mLogic.isManager(true);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private synchronized void matchFingerPrint() {
		mProgressDialog.setIsOut(true);
		mProgressDialog.setMessage("请按手指...");
		mProgressDialog.show();
		mLogic.execute();
		mProgressDialog.setMatchLogic(mLogic);
	}
	
	private Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			matchFingerPrint();
		}

	};

	// 关闭弹出框
	private void closeProgressDialog() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
		Toast.makeText(mContext, "登录失败，请切换登录方式", Toast.LENGTH_SHORT).show();
	}

	private Handler mFingerpringHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Message message = new Message();
			switch (msg.what) {
			case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
				break;
			case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
			case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
			case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
			case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
			case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
			case UIHelper.FINGERPRINT_SEARCH_FAIL:
				if (mActivity.isFinishing()) {
					return;
				}
				mCount --;
				if (mCount == 0) {
					closeProgressDialog();
				}else {
					if (mProgressDialog != null) {
						mProgressDialog.dismiss();
					}
					Toast.makeText(mContext, "匹配失败，请重试", Toast.LENGTH_SHORT);
					new Handler().postDelayed(mRunnable, LOADING_TIME);
				}
				break;
			case UIHelper.FINGERPRINT_SEARCH_SUCCESS:
				//匹配成功
				int pageId = msg.arg1;
				message.what = 100;
				message.arg1 = pageId;
				mLoginHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
				if (mActivity.isFinishing()) {
					return;
				}
				mProgressDialog.setIsOut(true);
				mProgressDialog.setMessage("请再次按指纹...");
				mProgressDialog.show();
			case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:
				break;

			default:
				break;
			}
		};

	};

	private void login() {
		LoginReq req = new LoginReq(HttpConfig.POST_URL_DATB_LOGIN,
				LoginSyncLogic.LOGIN_FINGERPRINT);

		LoginSyncLogic logic = new LoginSyncLogic(mAppContext, mContext,
				mLoginHandler, true, req);
		logic.execute();

	}

	private Handler mLoginHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			switch (msg.what) {
			case UIHelper.LOGIN_SUCCESS:
				if (mProgressDialog != null) {
					mProgressDialog.setIsOut(true);
					mProgressDialog.setMessage("请按手指...");
					mProgressDialog.show();
				}
				int count = msg.arg1;
				Log.i(TAG, "mLoginHandler count:" + count);
				if (count > 0) {
					// 开启指纹登录;
					mUserBeans = (List<UserBean>) msg.obj;
					Log.i(TAG, "mLoginHandler mCount:" + 0 + ",mSize:"
							+ mSize);
					matchFingerPrint();
				}
				break;
			case UIHelper.LOGIN_FAIL:
				closeProgressDialog();
				break;
			case 100:
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
				int id = msg.arg1;
				Log.i(TAG, "----->mLoginHandler id:" + id);
				FingerPrintBean fingerBean = mKjdb.findById(id,
						FingerPrintBean.class);
				Log.i(TAG, "---00-->mLoginHandler :" + fingerBean);
				if (fingerBean != null && fingerBean.getType() == 2) {
					String userId = fingerBean.getUserId();
					List<UserBean> userBeans = mKjdb.findAllByWhere(
							UserBean.class, "userId = " + userId);
					if(userBeans != null && !userBeans.isEmpty()){
						UserBean bean = userBeans.get(0);
						Log.i(TAG, "---11-->mLoginHandler :" + bean);
						if (bean != null) {
							// 添加登录日志
							
							AddLoginInfoReq req = new AddLoginInfoReq();
							req.setType(1);
							req.setLoginName(bean.getLoginName());
							req.setUserName(bean.getUserName());
							req.setOrganId(String.valueOf(bean.getOrganId()));
							req.setOrgan(bean.getOrgan());
							Log.i(TAG, "mLoginHandler req" + req);
							DatbAddLoginSyncLogic logic = new DatbAddLoginSyncLogic(
									mAppContext, mLoginHandler, false, req);
							logic.execute();
							// 保存当前登录信息
							// 保存用户信息
							PreferenceHelper.saveLoginInfoToPreference(mContext, bean);
							((AppContext) mContext.getApplicationContext())
									.setUserBean(bean);
							Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
							Intent intent = new Intent(mActivity, HomeActivity.class);
							intent.putExtra("is_to_loading_activity",true);
							startActivity(intent);
							KJActivityManager.create().finishActivity(mActivity);
						}else {
							closeProgressDialog();
						}
					}
				}else {
					closeProgressDialog();
				}
				break;

			default:
				
				break;
			}

		};
	};
	
	@Override
	public void onStop() {
		if (mLogic != null) {
			mLogic.destory();
		}
		super.onStop();
	};
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onDestroy()
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.fingerprint_img_tip:
				//重试
				mCount = 3;
				matchFingerPrint();
				break;
			case R.id.fingerprint_back:
				mActivity.finish();
				break;
			default:
				break;
		}
		
	}

}
